'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/hooks/use-auth'

interface PermissionGuardProps {
  children: React.ReactNode
  requireAuth?: boolean
  requireAdmin?: boolean
  requireCreate?: boolean
  requireDelete?: boolean
  fallback?: React.ReactNode
  className?: string
}

export function PermissionGuard({
  children,
  requireAuth = false,
  requireAdmin = false,
  requireCreate = false,
  requireDelete = false,
  fallback = null,
  className
}: PermissionGuardProps) {
  const { user, loading, permissions } = useAuth()
  const [hasPermission, setHasPermission] = useState(false)

  useEffect(() => {
    if (loading) {
      setHasPermission(false)
      return
    }

    // 检查基本认证
    if (requireAuth && !user) {
      setHasPermission(false)
      return
    }

    // 检查管理员权限
    if (requireAdmin && (!permissions?.canManageUsers && !permissions?.canEditAll)) {
      setHasPermission(false)
      return
    }

    // 检查创建权限
    if (requireCreate && (!permissions?.canEditAll && (!permissions?.dataSourceAccess || permissions.dataSourceAccess.length === 0))) {
      setHasPermission(false)
      return
    }

    // 检查删除权限
    if (requireDelete && (!permissions?.canEditAll && !permissions?.canManageUsers)) {
      setHasPermission(false)
      return
    }

    setHasPermission(true)
  }, [user, loading, permissions, requireAuth, requireAdmin, requireCreate, requireDelete])

  if (loading) {
    return (
      <div className={className}>
        <div className="animate-pulse bg-gray-200 rounded h-8 w-16"></div>
      </div>
    )
  }

  if (!hasPermission) {
    return fallback ? <div className={className}>{fallback}</div> : null
  }

  return <div className={className}>{children}</div>
}

export function usePermissions() {
  const { user, loading, permissions } = useAuth()

  return {
    loading,
    isAuthenticated: !!user,
    isAdmin: !!(permissions?.canManageUsers || permissions?.canEditAll),
    canCreate: !!(permissions?.canEditAll || (permissions?.dataSourceAccess && permissions.dataSourceAccess.length > 0)),
    canDelete: !!(permissions?.canEditAll || permissions?.canManageUsers),
    canEdit: !!(permissions?.canEditAll || (permissions?.dataSourceAccess && permissions.dataSourceAccess.length > 0)),
    user,
    permissions
  }
}